package com.dayuanit.dy11.mall.mallspringboot.service;

import com.dayuanit.dy11.mall.mallspringboot.dto.CartDTO;
import com.dayuanit.dy11.mall.mallspringboot.entity.Cart;
import com.dayuanit.dy11.mall.mallspringboot.entity.CommodityWithBLOBs;
import com.dayuanit.dy11.mall.mallspringboot.enums.CartStatusEnum;
import com.dayuanit.dy11.mall.mallspringboot.exception.BizException;
import com.dayuanit.dy11.mall.mallspringboot.mapper.CartMapper;
import com.dayuanit.dy11.mall.mallspringboot.mapper.CommodityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommoService {

    @Value("${book.img}")
    private String picUrl;

    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private CartMapper cartMapper;

    public CommodityWithBLOBs loadCommo(int id) {
        final CommodityWithBLOBs commodityWithBLOBs = commodityMapper.selectByPrimaryKey(id);
        commodityWithBLOBs.setPictureUrl(picUrl + commodityWithBLOBs.getPictureUrl());
        return commodityWithBLOBs;
    }

    public void addCart(int commoId, int buyNum, int userId) {

        //校验商品是否已经存在购物车
        final int count = cartMapper.countCartExit(userId, commoId);
        if (count > 0) {
            final Cart cart = cartMapper.getCart(userId, commoId);
            cart.setBuyNum(cart.getBuyNum() + buyNum);
            cartMapper.updateByPrimaryKey(cart);
            return;
        }

        final Cart cart = new Cart();
        cart.setBuyNum(buyNum);
        cart.setCommoId(commoId);
        cart.setCreateTime(new Date());
        cart.setModifyTime(new Date());
//        cart.setStatus(1);//TODO 使用枚举 不要直接写 这就是魔数 过两天你就不知道了
        cart.setStatus(CartStatusEnum.enable.getK());//推荐此种写法
        cart.setUserId(userId);
        int rows = cartMapper.insert(cart);
        if (1 != rows) {
            throw new BizException("添加购物车失败");
        }
    }

    public List<CartDTO> listCart(int userId) {
        final List<Cart> carts = cartMapper.listCart(userId);
        List<CartDTO> cartDTOS = new ArrayList<>(carts.size());

        for (Cart cart : carts) {
            final CartDTO cartDTO = new CartDTO();
            cartDTOS.add(cartDTO);

            cartDTO.setBuyNum(cart.getBuyNum());
            cartDTO.setCartId(cart.getId());
            final CommodityWithBLOBs commodityWithBLOBs = commodityMapper.selectByPrimaryKey(cart.getCommoId());

            cartDTO.setCommoId(cart.getCommoId());
            cartDTO.setCommoName(commodityWithBLOBs.getCommoName());
            cartDTO.setCommoPicUrl(picUrl + commodityWithBLOBs.getPictureUrl());
            cartDTO.setPrice(commodityWithBLOBs.getPrice());
        }

        return cartDTOS;
    }
}
